<div x-data="alpineContacts()" x-init="initPage()">
    <div>
        <h2>Contacts</h2>
        <p>
            <b>Contacts are touch points for agents.</b> A contact is a connection point on the server for agents to communicate through. Agents can be
            custom written against one (or multiple) contacts. Each contact logs all agent connections - and
            all commands it hands out. Download a report for any contact below.
        </p>
    </div>
    <hr>
    <div>
        <div class="buttons">
            <button class="button is-primary is-small" @click="initPage()">
                <span class="icon"><i class="fas fa-sync"></i></span>
                <span>Refresh</span>
            </button>
        </div>
        <table class="table is-striped">
            <tbody>
                <template x-for="contact of contacts" :key="contact.name">
                    <tr>
                        <th x-text="contact.name"></th>
                        <td x-text="contact.description"></td>
                        <td>
                            <span x-show="hasNoReport.includes(contact.name)" class="is-size-7">No contacts to show</span>
                            <button class="button is-small is-primary" @click="downloadContactReport(contact.name)" x-show="!hasNoReport.includes(contact.name)">
                                <span class="icon"><i class="fas fa-file-download"></i></span>
                                <span>Download Report</span>
                            </button>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>
</div>

<script>
    function alpineContacts() {
        return {
            contacts: JSON.parse('{{ contacts | tojson }}'),
            hasNoReport: [],

            initPage() {
                this.hasNoReport = [];
                this.contacts.forEach(async (contact) => {
                    try {
                        await apiV2('GET', `/api/v2/contacts/${contact.name}`);
                    } catch (error) {
                        this.hasNoReport.push(contact.name);
                    }
                });
            },

            downloadContactReport(contactName) {
                apiV2('GET', `/api/v2/contacts/${contactName}`).then((contact) => {
                    downloadJson(`${contactName}_contact_report`, contact);
                }).catch((error) => {
                    toast('Error loading page', false);
                    console.error(error);
                });
            }
        };
    }

    // # sourceURL=contacts.js
</script>
